package com.seadragon.app.ksr.service.impl;

import static com.seadragon.app.ksr.model.KsrConstants.GEOCODED_THRESHOLD;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.seadragon.app.ksr.dao.GeocodedAddressDao;
import com.seadragon.app.ksr.dao.ZipLookUpDao;
import com.seadragon.app.ksr.model.Address;
import com.seadragon.app.ksr.model.GeocodedAddress;
import com.seadragon.app.ksr.service.GeocodeService;

public class GeocodeServicePostgisImpl implements GeocodeService {
	@Autowired
	private GeocodedAddressDao geocodedAddressDao;
	@Autowired
	private ZipLookUpDao zipLookUpDao;
	
	@Override
	public GeocodedAddress geocode(Address address) {
		GeocodedAddress result = geocode(address.toRawString());
		if(result.isAddress()){
			if(result.getRating() < GEOCODED_THRESHOLD){
				address.setStreetNumber(result.getStreetNumber());
				address.setStreetName(result.getStreetName());
				address.setStreetType(result.getStreetType());
				if(result.getPreDir() != null){
					address.setPreDir(result.getPreDir());
				}
				if(result.getPostDir() != null){
					address.setPostDir(result.getPostDir());
				}
				if(result.getInternal() != null){
					address.setInternal(result.getInternal());
				}
				address.setLocation(result.getPos());
				address.setGeocodedCity(result.getCity());
				address.setGeocodedCounty(zipLookUpDao.findCountyByZip(result.getZip()));
				address.setGeocodedState(result.getState());
				address.setGeocodedZip(result.getZip());
			}
		}
		return result;
	}

	@Override
	public GeocodedAddress geocode(String addressString) {
		List<GeocodedAddress> normalizedAddresses = geocodedAddressDao.geocode(addressString);
		if(normalizedAddresses == null || normalizedAddresses.size() == 0) return null;
		if(normalizedAddresses.get(0).isAddress()){
			List<GeocodedAddress> addresses = geocodedAddressDao.geocode(addressString);
			if(addresses == null || addresses.size() == 0) return null;
			return addresses.get(0);			
		}else if(normalizedAddresses.get(0).isZip()){
			
		}else if(normalizedAddresses.get(0).isCity()){
			
		}else if(normalizedAddresses.get(0).isZip()){
			
//		}else if(normalizedAddresses.get(0).isCounty()){
//			
//		}else if(normalizedAddresses.get(0).isState()){
//			
		}
		return null;
	}

	@Override
	public GeocodedAddress normalize(String addressString) {
		List<GeocodedAddress> addresses = geocodedAddressDao.normalize(addressString);
		if(addresses == null || addresses.size() == 0) return null;
		return addresses.get(0);
	}
}
